<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        /* 
        二叉树的直径
        1.递归法：
          时间复杂度O(n)
          空间O(n)
        */
        function diameterOfBinaryTree(root) {
            let ans = 0
            function dfs (node) {
                if (!node) {
                    return -1
                }
                // 求左右各自的链长
                let lLen = dfs(node.left) + 1
                let rLen = dfs(node.right) + 1
                // 在当前这个节点拐弯，左+右形成的一个路径
                ans = Math.max(ans, lLen + rLen)
                // 注意，返回的不是lLen+rLen，因为左加上右无论怎么组合都无法是一条路径，会右两个叶子节点
                return Math.max(lLen, rLen)
            }
            dfs(root)
            return ans
        }

        function Node(val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }
        var a = new Node(1)
        var b = new Node(2)
        var c = new Node(3)
        var d = new Node(4)
        var e = new Node(5)
        var f = new Node(6)
        a.left = b
        a.right = c
        b.left = d
        b.right = e
        e.left = f
        console.log(diameterOfBinaryTree(a));
    </script>
</body>

</html>